#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define KEY 6
char *keyword[KEY] = {"for", "if", "then", "else", "while", "do"};
char id[1024];
int num;
int token;

void lexical(FILE *fp) {
	char x = getc(fp);

	num = 0;
	strcpy(id, "\0");
	while(x==' '||x=='\t'||x=='\n')
	{
		x=getc(fp);
	}
	int i=0;
	int j=0;
	char temp;
	if((x<='z')&&(x>='a')||(x<='Z')&&(x>='A'))
	{
	id[i++]=x;
	temp=getc(fp);
	while((temp<='z')&&(temp>='a')||(temp<='Z')&&(temp>='A')||(temp<=9)&&(temp>=0))
		{
		id[i++]=temp;
		temp=getc(fp);
		}
	ungetc(temp,fp);
	id[i++]='\0';
	for(j;j<6;j++)
		{
		if(strcmp(id,keyword[j])==0)
		{
			token=j+1;
			break;
		}
		}
		if(j==6)
		token=10;
	}
	else if(x>='0'&&x<='9')
	{
	id[i++]=x;
	temp=getc(fp);
	while(temp>='0'&&temp<='9')
	{
		id[i++]=x;
		temp=getc(fp);
	}
	id[i++]='\0';
	ungetc(temp,fp);
	i=0;
	while(id[i]!='\0')
	{
		temp=id[i]-'\0';
		num=num*10+temp;
		i++;
	}
	token=11;
	}
	else if(x=='+')
	{
	id[i++]='+';
	token=13;
	id[i++]='\0';
	}
	else if(x=='-')
	{
        id[i++]='-';
        token=14;
	id[i++]='\0';
	}
	else if(x=='*')
	{
	id[i++]='*';
        token=15;
        id[i++]='\0';
	}
	else if(x=='/')
	{
	id[i++]='/';
	token=16;
	id[i++]='\0';
	}
	else if(x==':')
	{
	id[i++]=':';
	temp=getc(fp);
	if(temp=='=')
	{
		id[i++]='=';
		token=18;
		id[i++]='\0';
	}
	else{
		ungetc(temp,fp);
		token=17;
		id[i++]='\0';
	}
	}
	else if(x=='<')
	{
	id[i++]='<';
	temp=getc(fp);
	if(temp=='>')
	{id[i++]='>';token=21;id[i++]='\0';}
	else if(temp=='=')
	{id[i++]='=';token=22;id[i++]='\0';}
	else
	{ungetc(temp,fp);token=20;id[i++]='\0';}
	}

	else if(x=='>')
	{id[i++]='>';temp=getc(fp);
	if(temp=='=')
	{id[i++]='=';token=24;id[i++]='\0';}
	else
	{ungetc(temp,fp);
	token=23;id[i++]='\0';}
	}

	else if(x=='=')
	{id[i++]=='=';
	token=25;
	id[i++]='\0';
	}
	
	else if(x==';')
        {id[i++]==';';
	token=26;
        id[i++]='\0';
        }

	else if(x=='(')
        {id[i++]=='(';
	token=27;
        id[i++]='\0';
        }

	else if(x==')')
        {id[i++]==')';
        token=28;
        id[i++]='\0';
        }

	else if(x=='#')
	{
	id[i++]='#';
	token=0;
	id[i++]='\0';
	}

	else
	{token=-1;}
	//process x
	//process each regex here
	//store the result in global variables id, num, or token
	//in case of backtrack, use
	//ungetc(x, fp);
	
}

int main(int argc, const char *argv[])
{
	if(argc < 2) {
	printf("insufficient args\n");
		return 1;
	}
	FILE *fp = fopen(argv[1], "r");
	do {
		lexical(fp);
		switch(token) {
			case 10: printf("(id, %s)\n", id); break;
			case 11: printf("(num, %d)\n", num); break;
			case -1: printf("error!\n"); break;
			default: printf("(%d, %s)\n", token, id); 		
		}
	} while(token != 0);
	

	fclose(fp);
	return 0;
}
